#!/bin/bash
set -e

script_dir=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
source "$script_dir/functions"

ENTITLEMENTS="$script_dir/$tbb_version_type.entitlements.xml"

function check_signature() {
  LANG=$1
  UNZIP=$2
  local failed_open=0
  local failed_exec=0
  if [ ${UNZIP} -eq 1 ]
  then
    test -d test_${LANG} && rm -r test_${LANG}
    unzip -d test_${LANG} -q tb-${tbb_version}_$LANG.zip
    pushd test_${LANG}
  fi
  echo "Checking $LANG..."
  spctl -vvvv --assess --type open --context context:primary-signature 'Tor Browser.app/'
  if [ $? -ne 3 ]; then
    echo tb-${tbb_version}_$LANG.zip not signed correctly. Failed open.
    failed_open=1
  fi
  spctl -vvvv --assess --type exec --context context:primary-signature 'Tor Browser.app/'
  if [ $? -ne 0 ]; then
    echo tb-${tbb_version}_$LANG.zip not signed correctly. Failed exec.
    failed_exec=1
  fi
  if [ ${UNZIP} -eq 1 ]
  then
    popd
    rm -r test_${LANG}
  fi
  if [ ${failed_open} -ne 0 -o ${failed_exec} -ne 0 ]
  then
    return 1
  fi
}

cd ~/${tbb_version}

if test -n "$KEYCHAIN_PW"
then
  KPW="-p $KEYCHAIN_PW"
fi

security unlock $KPW /Users/torbrowser/Library/Keychains/tbb-signing-alpha.keychain
security unlock $KPW /Users/torbrowser/Library/Keychains/tbb-signing-2021.keychain

unset KPW KEYCHAIN_PW

for LANG in $bundle_locales
do
  if [ -f tb-${tbb_version}_${LANG}.zip ]
  then
    echo "Deleting tb-${tbb_version}_${LANG}.zip"
    rm tb-${tbb_version}_${LANG}.zip
  fi
  if [ -d "Tor Browser.app" ]
  then
    echo "Deleting Tor Browser.app"
    rm -r "Tor Browser.app"
  fi
  if [ -d '/Volumes/Tor Browser' ]; then
    echo "DMG already mounted. Please correct."
    exit 1
  fi
  hdiutil attach TorBrowser-${tbb_version}-osx64_$LANG.dmg
  cp -rf "/Volumes/Tor Browser/Tor Browser.app" "Tor Browser.app"
  echo "Signing Tor Browser_$LANG.app"
  codesign -vvv --deep -o runtime --entitlements="$ENTITLEMENTS" --timestamp -f -s "Developer ID Application: The Tor Project, Inc (MADPSAYN6T)" "Tor Browser.app/"
  echo "codesign exit code: $?"
  set +e
  check_signature $LANG 0
  if [ $? -eq 1 ]
  then
    echo Signature verification failed.
    rm -r "Tor Browser.app"
    hdiutil detach "/Volumes/Tor Browser"
    exit 1
  fi
  set -e
  echo "Zipping up tb-${tbb_version}_${LANG}.zip"
  zip -qr tb-${tbb_version}_${LANG}.zip "Tor Browser.app"
  rm -rf "Tor Browser.app"
  hdiutil detach "/Volumes/Tor Browser"
  set +e
  check_signature $LANG 1
  if [ $? -eq 1 ]
  then
    echo Signature verification failed ($LANG).
    rm -r "Tor Browser.app"
    exit 1
  fi
  set -e
done
